package com.liufh.service.impl;

import com.liufh.common.ResultData;
import com.liufh.dao.TokenDao;
import com.liufh.dao.UserDao;
import com.liufh.feign.CodeServiceFeignClient;
import com.liufh.pojo.Token;
import com.liufh.pojo.User;
import com.liufh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author: liufh
 * @create: 2022-01-25 17:18
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private CodeServiceFeignClient feignClient;

    @Override
    public String register(String email, String password, String code) {
        ResultData validate = feignClient.validate(email, code);
        if ("0".equals(validate.getCode())) {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            userDao.save(user);
            return "0";
        }
        return null;
    }

    @Override
    public ResultData login(String email, String password, HttpServletResponse response) {
        // 校验账号密码
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Example<User> example = Example.of(user);
        try {
            User authCodeRes = userDao.findOne(example).get();
        } catch (Exception e) {
            return ResultData.fail(response, "ok", "账号密码不正确，请重新输入!");
        }

        // 生成token
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();

        // 保存token
        Token tokenSave = new Token();
        tokenSave.setEmail(email);
        tokenSave.setToken(token);
        tokenDao.save(tokenSave);

        return ResultData.success(response, token, "success", "0");
    }

    @Override
    public String userInfo(String token) {
        Token tokenC = new Token();
        tokenC.setToken(token);
        Example<Token> example = Example.of(tokenC);
        String email = null;
        try {
            Token userInfo = tokenDao.findOne(example).get();
            email = userInfo.getEmail();
        } catch (Exception e) {
        }
        return email;
    }

}
